package com.mentalhealthplatform.studentV3.controller;


import com.mentalhealthplatform.exception.user.UserNotFoundException;
import com.mentalhealthplatform.global.debounce.Debounce;
import com.mentalhealthplatform.global.log.manager.ManagerLogAction;
import com.mentalhealthplatform.global.rbac.dto.normal.BaseUserDTO;
import com.mentalhealthplatform.global.rbac.model.CustomUserDetails;
import com.mentalhealthplatform.global.rbac.model.User;
import com.mentalhealthplatform.global.rbac.service.relation.UserRoleService;
import com.mentalhealthplatform.studentV3.dto.UserDTOV3;
import com.mentalhealthplatform.studentV3.service.BaseUserServiceV3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;


/**
 * @author Pear
 */
@RestController
@RequestMapping("/api/v3/users/")
public class UserControllerV3 {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private BaseUserServiceV3 userService;
    @Autowired
    private BaseUserServiceV3 baseUserServiceV3;

    // 根据用户 ID 获取用户及其角色信息
    @GetMapping("/{id}")
    @Debounce
    @PreAuthorize("hasAuthority('USER:READ') or #id == authentication.principal.id")
    public BaseUserDTO getUser(@PathVariable UUID id) {
        return userRoleService.getUserById(id);
    }

    // 新增用户
    @PostMapping
    @ManagerLogAction(module = "用户管理", operationType = "新增", description = "添加新用户")
    @Debounce
    @PreAuthorize("hasAuthority('USER:CREATE')")
    public ResponseEntity<?> addUser(@RequestBody UserDTOV3 userDTO) {
        User newUser = baseUserServiceV3.addUser(userDTO);
        return ResponseEntity.status(201).body(UserDTOV3.fromUser(newUser));
    }


    // 获取所有用户及其角色信息
    @GetMapping
    @Debounce
    @PreAuthorize("hasAuthority('USER:READ_ALL')")
    public List<BaseUserDTO> getAllUsers() {
        return userRoleService.getAllUsers();
    }

    // 更新用户信息
    @PutMapping("/{id}")
    @Debounce
    @PreAuthorize("hasAuthority('USER:UPDATE') or #id == authentication.principal.id")
    public ResponseEntity<String> updateUser(@PathVariable UUID id, @RequestBody UserDTOV3 userDTO) {
        // 如果用户名重复或用户不存在，会抛出异常
        baseUserServiceV3.updateUser(id, userDTO);
        return ResponseEntity.status(200).body("用户信息更新成功");
    }

    // 切换用户状态
    @PutMapping("/{id}/status")
    @Debounce
    @PreAuthorize("hasAuthority('USER:STATUS_UPDATE')")
    public ResponseEntity<?> updateUserStatus(@PathVariable UUID id, @RequestBody Map<String, Boolean> status) {
        // 如果用户不存在，会抛出异常
        baseUserServiceV3.updateUserStatus(id, status.get("status"));
        return ResponseEntity.ok().build();
    }

    // 删除用户
    @DeleteMapping("/{id}")
    @ManagerLogAction(module = "用户管理", operationType = "删除", description = "删除用户")
    @Debounce
    @PreAuthorize("hasAuthority('USER:DELETE') and #id != authentication.principal.id")
    public ResponseEntity<?> deleteUser(@PathVariable UUID id) {
        baseUserServiceV3.deleteUser(id);
        return ResponseEntity.ok().build();
    }

    // 批量删除用户
    @PostMapping("/delete")
    @Debounce
    @PreAuthorize("hasAuthority('USER:DELETE_ALL')")
    public ResponseEntity<?> deleteUsers(@RequestBody List<UUID> ids) {
        ids.forEach(baseUserServiceV3::deleteUser);
        return ResponseEntity.ok().build();
    }

    // 授予角色给用户
    @PostMapping("/{userId}/roles/add/{roleId}")
    @Debounce
    @PreAuthorize("hasAuthority('USER:ROLE_ASSIGN')")
    public ResponseEntity<String> addRoleToUser(@PathVariable UUID userId, @PathVariable Long roleId) {
        userRoleService.addRoleToUser(userId, roleId);
        return ResponseEntity.status(200).body("角色授予成功");
    }

    // 撤销用户的角色
    @PostMapping("/{userId}/roles/remove/{roleId}")
    @Debounce
    @PreAuthorize("hasAuthority('USER:ROLE_REMOVE')")
    public ResponseEntity<String> removeRoleFromUser(@PathVariable UUID userId, @PathVariable Long roleId) {
        userRoleService.removeRoleFromUser(userId, roleId);
        return ResponseEntity.status(200).body("角色撤销成功");
    }
    @GetMapping("/user/name")
    public ResponseEntity<UserDTOV3> getUserIdByName(@RequestParam String name) {
        UserDTOV3 user = baseUserServiceV3.findUserByName(name);
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }

    // 获取当前用户电话信息
    @GetMapping("/current")
    @Debounce
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<Map<String, String>> getCurrentUser() {
        CustomUserDetails userDetails = (CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UUID userId = userDetails.getId();
        Optional<User> userOptional = baseUserServiceV3.getUserById(userId);
        if (userOptional.isPresent()) {
            User user = userOptional.get();
            UserDTOV3 userDTO = convertToUserdtoV3(user);
            Map<String, String> response = Map.of("phone", userDTO.getPhone());
            return ResponseEntity.ok(response);
        } else {
            // 如果用户不存在，抛出 UserNotFoundException 或返回其他错误信息
            throw new UserNotFoundException("用户未找到");
        }
    }

    private UserDTOV3 convertToUserdtoV3(User user) {
        UserDTOV3 userDTO = new UserDTOV3();
        userDTO.setId(user.getId());
        userDTO.setPhone(user.getPhone());
        // 设置其他需要的属性
        return userDTO;
    }


    @PutMapping("/{id}/update-phone")
    public ResponseEntity<String> updateUserPhone(@PathVariable UUID id, @RequestBody Map<String, String> request) {
        String phone = request.get("phone");

        if (phone == null || !phone.matches("^[0-9]{10,11}$")) {
            throw new IllegalArgumentException("电话号码格式不正确");
        }

        baseUserServiceV3.updateUserPhone(id, phone);
        return ResponseEntity.ok("电话更新成功");
    }

    @PutMapping("/{id}/update-password")
    public ResponseEntity<String> updateUserPassword(@PathVariable UUID id, @RequestBody Map<String, String> request) {
        String oldPassword = request.get("oldPassword");
        String newPassword = request.get("newPassword");

        if (oldPassword == null || newPassword == null || newPassword.length() < 6) {
            throw new IllegalArgumentException("密码不能为空，且新密码长度不能少于6位");
        }

        baseUserServiceV3.updateUserPassword(id, oldPassword, newPassword);
        return ResponseEntity.ok("密码更新成功");
    }
}
